package org.jeecg.modules.demo.doc.controller;

import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import freemarker.template.utility.StringUtil;
import org.apache.commons.io.IOUtils;
import org.apache.poi.poifs.filesystem.DirectoryEntry;
import org.apache.poi.poifs.filesystem.DocumentEntry;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.xwpf.usermodel.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.dom4j.Document;
import org.dom4j.util.StringUtils;
import org.hibernate.validator.internal.util.privilegedactions.GetResource;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.controller.CommonController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.MsOffice2Pdf;
import org.jeecg.modules.demo.doc.entity.Doc;
import org.jeecg.modules.demo.doc.service.IDocService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.system.entity.DocHistory;
import org.jeecg.modules.system.entity.DocHistoryCopy;
import org.jeecg.modules.system.entity.SysCategory;
import org.jeecg.modules.system.service.IDocHistoryCopyService;
import org.jeecg.modules.system.service.IDocHistoryService;
import org.jeecg.modules.system.service.ISysCategoryService;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.xhtmlrenderer.pdf.ITextRenderer;


/**
 * @Description: 文档
 * @Author: jeecg-boot
 * @Date: 2020-04-02
 * @Version: V1.0
 */
@SuppressWarnings("All")
@Api(tags = "文档")
@RestController
@RequestMapping("/doc/doc")
@Slf4j
public class DocController extends JeecgController<Doc, IDocService> {

    @Value(value = "${jeecg.path.upload}")
    private String uploadpath;
    @Autowired
    private IDocService docService;
    @Autowired
    private ISysCategoryService sysCategoryService;
    @Autowired
    private IDocHistoryCopyService iDocHistoryCopyService;
    @Autowired
    private IDocHistoryService docHistoryService;

    /**
     * 添加
     *
     * @param doc
     * @return
     */
    @AutoLog(value = "文档-恢复")
    @ApiOperation(value = "文档-恢复", notes = "文档-恢复")
    @RequestMapping(value = "/recover")
    public Result<?> recover(@RequestBody Doc doc) {
        docService.updateById(doc);
        return Result.ok("恢复成功！");
    }

    /**
     * 统计
     */
    @GetMapping(value = "/count")
    public Result<?> count() {
        //统计总文档量
        Integer docCount = docService.docCount();
        //统计JCI文档量
        Integer jciCount = docService.jciCount();
        //统计过期文档
        Integer isExpired = docService.isExpired();
        //统计总浏览量
        Integer readCount = docService.readCount();
        Integer[] result = {docCount, jciCount, isExpired, readCount};
        return Result.ok(result);
    }

    /**
     * 修改日期
     */
    @RequestMapping(value = "/dateChange")
    public Result<?> dateChange(@RequestBody Doc doc) {
        docService.updateById(doc);
        return Result.ok("修改成功");
    }

    /**
     * 批量修日期
     */
    @RequestMapping(value = "/batchDateUpdate")
    public Result<?> batchDateUpdate(@RequestBody JSONObject jsonObject) throws ParseException {
        if (jsonObject.equals(null)) {
            return Result.ok("修改失败");
        }
        JSONArray ids = jsonObject.getJSONArray("ids");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String date = jsonObject.getString("date");
        if (date.equals("sx")) {
            String sxTime = jsonObject.getString("sxTime");
            Date parse = simpleDateFormat.parse(sxTime);
            for (int i = 0; i < ids.size(); i++) {
                String id = (String) ids.get(i);
                Doc doc = docService.getById(id);
                doc.setSxTime(parse);
                docService.updateById(doc);
            }
        } else if (date.equals("dq")) {
            for (int i = 0; i < ids.size(); i++) {
                String dqTime = jsonObject.getString("dqTime");
                Date parse = simpleDateFormat.parse(dqTime);
                String id = (String) ids.get(i);
                Doc doc = docService.getById(id);
                doc.setDqTime(parse);
                docService.updateById(doc);
            }
        }
        return Result.ok("修改成功");
    }

    /**
     * 查询单条记录
     */
    @GetMapping("/selectOne")
    public Result<?> selectOne(@RequestParam("id") String id) {
        Result<Doc> docResult = new Result<>();
        Doc doc = docService.selectOne(id);
        return Result.ok(doc);
    }

    /**
     * 分页列表查询
     *
     * @param doc
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "文档-分页列表查询")
    @ApiOperation(value = "文档-分页列表查询", notes = "文档-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(Doc doc,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "1000") Integer pageSize,
                                   HttpServletRequest req) {
        String docExpired=doc.getDocExpired();
        doc.setDocExpired(null);
        QueryWrapper<Doc> queryWrapper = QueryGenerator.initQueryWrapper(doc, req.getParameterMap());
        Page<Doc> page = new Page<Doc>(pageNo, pageSize);
        IPage<Doc> pageList = docService.page(page, queryWrapper);
        List<Doc> records = pageList.getRecords();
        List<Doc> record=new ArrayList<>();
         if(docExpired!=null){
             if (docExpired.equals("1")){
                 for (int i = 0; i < records.size(); i++) {
                     Doc doc1 = records.get(i);
                     if (doc1.getDqTime().getTime()<new Date().getTime()){
                         doc1.setDocExpired("1");
                         record.add(doc1);
                     }
                 }
                 pageList.setRecords(record);
             }else if (docExpired.equals("0")){
                 for (int i = 0; i < records.size(); i++) {
                     Doc doc1 = records.get(i);
                     if (doc1.getDqTime().getTime()>=new Date().getTime()){
                         doc1.setDocExpired("0");
                         record.add(doc1);
                     }
                 }
                 pageList.setRecords(record);
             }
         }
        else {
            for (int i = 0; i < records.size(); i++) {
                Doc doc1 = records.get(i);
                if (doc1.getDqTime()!=null){
                    if (doc1.getDqTime().getTime()<new Date().getTime()){
                        doc1.setDocExpired("1");
                    }else {
                        doc1.setDocExpired("0");
                    }
                }
            }
        }
        return Result.ok(pageList);
    }


    /**
     * 添加
     *
     * @param doc
     * @return
     */
    @AutoLog(value = "文档-添加")
    @ApiOperation(value = "文档-添加", notes = "文档-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody Doc doc) {
        SysCategory category = sysCategoryService.getById(doc.getDocCategory());
        doc.setCategoryName(category.getName());
        doc.setPid(category.getPid());
        docService.save(doc);
        DocHistory docHistory = new DocHistory();
        docHistory.setId(doc.getId());
        docHistory.setDocName(doc.getDocName());
        docHistory.setOperator(doc.getCreateBy());
        docHistory.setOperation("创建");
        docHistory.setOperationTime(doc.getCreateTime());
        docHistoryService.save(docHistory);
        return Result.ok("添加成功！");
    }

    /**
     * 添加
     *
     * @param doc
     * @param doc
     * @return
     */
    @AutoLog(value = "文档-添加")
    @ApiOperation(value = "文档-添加", notes = "文档-添加")
    @PostMapping(value = "/addEditor")
    public Result<?> addEditor(@RequestBody Doc doc) {

        if (doc.getDownload()==null){
            doc.setDownload(0);
        }
        if (doc.getPrint()==null){
            doc.setPrint(0);
        }
        SysCategory category = sysCategoryService.getById(doc.getDocCategory());
        doc.setCategoryName(category.getName());
        doc.setPid(category.getPid());
        docService.save(doc);
        DocHistory docHistory = new DocHistory();
        docHistory.setId(doc.getId());
        docHistory.setDocName(doc.getDocName());
        docHistory.setOperator(doc.getCreateBy());
        docHistory.setOperation("创建");
        docHistory.setOperationTime(doc.getCreateTime());
        docHistoryService.save(docHistory);
        return Result.ok("添加成功！");
    }

    /**
     * 编辑
     *
     * @param doc
     * @return
     */
    @AutoLog(value = "文档-编辑")
    @ApiOperation(value = "文档-编辑", notes = "文档-编辑")
    @RequestMapping(value = "/edit")
    public Result<?> edit(@RequestBody Doc doc) {
        Doc byId = docService.getById(doc.getId());
        DocHistoryCopy docHistoryCopy = new DocHistoryCopy();
        docHistoryCopy.setPid(doc.getPid());
        docHistoryCopy.setId(byId.getId());
        docHistoryCopy.setCreateBy(byId.getCreateBy());
        docHistoryCopy.setCreateTime(byId.getCreateTime());
        docHistoryCopy.setUpdateBy(byId.getUpdateBy());
        docHistoryCopy.setUpdateTime(byId.getUpdateTime());
        docHistoryCopy.setUpTime(byId.getUpTime());
        docHistoryCopy.setSysOrgCode(byId.getSysOrgCode());
        docHistoryCopy.setCategoryName(byId.getCategoryName());
        docHistoryCopy.setDocCategory(byId.getDocCategory());
        docHistoryCopy.setDocName(byId.getDocName());
        docHistoryCopy.setDocNo(byId.getDocNo());
        docHistoryCopy.setDzDepartment(byId.getDzDepartment());
        docHistoryCopy.setDocSize(byId.getDocSize());
        docHistoryCopy.setJic(byId.getJic());
        docHistoryCopy.setSxTime(byId.getSxTime());
        docHistoryCopy.setDqTime(byId.getDqTime());
        docHistoryCopy.setIsJic(byId.getIsJic());
        docHistoryCopy.setDownload(byId.getDownload());
        docHistoryCopy.setPrint(byId.getPrint());
        docHistoryCopy.setAudit(byId.getAudit());
        docHistoryCopy.setEditor(byId.getEditor());
        docHistoryCopy.setDocExpired(byId.getDocExpired());
        docHistoryCopy.setDocStatus(byId.getDocStatus());
        docHistoryCopy.setFileKk(byId.getFileKk());
        iDocHistoryCopyService.removeById(byId.getId());
        iDocHistoryCopyService.save(docHistoryCopy);
        SysCategory category = sysCategoryService.getById(doc.getDocCategory());
        doc.setCategoryName(category.getName());
        docService.updateById(doc);
        Doc newDoc = docService.getById(doc.getId());
        DocHistory docHistory = new DocHistory();
        docHistory.setId(byId.getId());
        docHistory.setDocName(newDoc.getDocName());
        docHistory.setOperator(newDoc.getUpdateBy());
        docHistory.setOperation("更新");
        docHistory.setOperationTime(newDoc.getUpdateTime());
        docHistoryService.save(docHistory);
        return Result.ok("编辑成功!");
    }

    /**
     * 启用
     *
     * @param doc
     * @return
     */
    @AutoLog(value = "文档-启用")
    @ApiOperation(value = "文档-启用", notes = "文档-启用")
    @RequestMapping(value = "/open")
    public Result<?> open(@RequestBody Doc doc) {
        doc.setDocStatus("0");
        docService.updateById(doc);
        return Result.ok("启用成功!");
    }

    /**
     * 禁用
     *
     * @param doc
     * @return
     */
    @AutoLog(value = "文档-禁用")
    @ApiOperation(value = "文档-禁用", notes = "文档-禁用")
    @RequestMapping(value = "/close")
    public Result<?> close(@RequestBody Doc doc) {
        doc.setDocStatus("1");
        docService.updateById(doc);
        return Result.ok("禁用成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "文档-通过id删除")
    @ApiOperation(value = "文档-通过id删除", notes = "文档-通过id删除")
    @RequestMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        // 根据id获取文件路径
       /* Doc doc = docService.getById(id);
        String path = uploadpath + File.separator + doc.getFileKk();
        File file = new File(path);
        // 如果文件存在则删除
        if (file.exists()) {
            if (docService.removeById(id)) { // 数据库删除成功则删除文件
                file.delete();
            }
            return Result.ok("删除成功!");
        } else {
            docService.removeById(id); // 文件不存在则删除数据
            return Result.error("未找到对应文件");
        }*/
        Doc doc = docService.getById(id);
        String path = uploadpath + File.separator + doc.getFileKk();
        String path1 = uploadpath + File.separator + doc.getDocName() + ".pdf";
        File file = new File(path);
        File file1 = new File(path1);
        if (file.exists()) {
            file.delete();
        }
        if (file1.exists()) {
            file1.delete();
        }
        docService.removeById(id);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "文档-批量删除")
    @ApiOperation(value = "文档-批量删除", notes = "文档-批量删除")
    @RequestMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.docService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "文档-通过id查询")
    @ApiOperation(value = "文档-通过id查询", notes = "文档-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        Doc doc = docService.getById(id);
        if (doc == null) {
            return Result.error("未找到对应数据");
        }
        return Result.ok(doc);
    }

    /**
     * 点击查看增加点击量
     */
    @GetMapping(value = "/addCount")
    @RequiresPermissions("read:count")
    public void addCount(@RequestParam(name = "id", required = true) String id) {
        Doc doc = docService.getById(id);
        int readCount = doc.getReadCount();
        doc.setReadCount(readCount + 1);
        docService.updateById(doc);
    }

    @RequestMapping(value = "/exportDocs")
    public void exportDocs(HttpServletRequest request, HttpServletResponse response,
                           @RequestParam(name = "docName", required = true) String docNames,
                           @RequestParam(name = "recordId", required = true) String recordIds) {
        try {
            //word内容
            List<String> listId = Arrays.asList(recordIds.split(","));
            List<String> listName = Arrays.asList(docNames.split(","));
            for (int i = 0; i < listId.size(); i++) {
                Doc doc = docService.getById(listId.get(i));
                String docName = listName.get(i);
                String content = "<html><body>" + doc.getEditor() + "</body></html>";
                byte b[] = content.getBytes("utf-8");  //这里是必须要设置编码的，不然导出中文就会乱码。
                ByteArrayInputStream bais = new ByteArrayInputStream(b);//将字节数组包装到流中
                /*
                 * 关键地方
                 * 生成word格式 */
                POIFSFileSystem poifs = new POIFSFileSystem();
                DirectoryEntry directory = poifs.getRoot();
                DocumentEntry documentEntry = directory.createDocument(docName, bais);
                //输出文件
                request.setCharacterEncoding("utf-8");
                response.setContentType("application/msword");//导出word格式
                System.out.println(documentEntry.toString() + "DAd" + documentEntry.getName());
                response.addHeader("Content-Disposition", "p_w_upload;filename=" +
                        new String((documentEntry.getName() + ".doc").getBytes(), "iso-8859-1"));
                OutputStream ostream = response.getOutputStream();
                poifs.writeFilesystem(ostream);
                bais.close();
                ostream.close();
            }
        } catch (Exception e) {
            //异常处理
        }
    }

    /**
     * 导出excel
     *
     * @param request
     * @param doc
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, Doc doc) {
        return super.exportXls(request, doc, Doc.class, "文档");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, Doc.class);
    }

    /**
     * 下载pdf
     *
     * @param request
     * @param response
     * @param docName
     * @param recordId
     */
    @RequestMapping(value = "/exportPDF")
    public void exportPDF(HttpServletRequest request, HttpServletResponse response,
                          @RequestParam(name = "docName", required = true) String docName,
                          @RequestParam(name = "recordId", required = true) String recordId) {
        OutputStream os = null;
        FileInputStream fs = null;
        Document document = null;
        try {
            //String path= GetResource.class.getClassLoader().getResource("pdf/"+ docName + ".pdf").getPath();
            String path = GetResource.class.getClassLoader().getResource("pdf/").getPath();
            //String path = "C:\\Users\\15754\\Desktop\\" + docName + ".pdf";
            path = path + docName + ".pdf";
            File file = new File(path);
            if (!file.exists()) {
                file.createNewFile();
            }
            os = new FileOutputStream(path);
            ITextRenderer renderer = new ITextRenderer();
            Doc doc = docService.getById(recordId);
            String content = "<html><body>" + doc.getEditor() + "</body></html>";
            renderer.setDocumentFromString(content);
            renderer.layout();
            renderer.createPDF(os);
            //输出文件
            response.setCharacterEncoding("utf-8");
            response.setLocale(new java.util.Locale("zh", "CN"));
            response.setContentType("application/pdf");//导出word格式
            response.addHeader("Content-Disposition", "attachment;filename=" +
                    new String((docName + ".pdf").getBytes(), "iso-8859-1"));
            fs = new FileInputStream(new File(path));
            OutputStream ostream = response.getOutputStream();
            byte[] bytes = new byte[512];
            while ((fs.read(bytes)) != -1) {
                ostream.write(bytes);
            }
            ostream.flush();
            fs.close();
            ostream.close();
        } catch (Exception e) {
            //异常处理
        }

    }

    @RequestMapping(value = "/exportDoc")
    public void exportDoc(HttpServletRequest request, HttpServletResponse response,
                          @RequestParam(name = "docName", required = true) String docName,
                          @RequestParam(name = "recordId", required = true) String recordId) {

        //word内容
        Doc doc = docService.getById(recordId);
        String content = "<html><body>" + doc.getEditor() + "</body></html>";
        try {
            // 生成doc格式的word文档，需要手动改为docx
            byte by[] = content.getBytes("UTF-8");
            ByteArrayInputStream bais = new ByteArrayInputStream(by);
            POIFSFileSystem poifs = new POIFSFileSystem();
            DirectoryEntry directory = poifs.getRoot();
            DocumentEntry documentEntry = directory.createDocument("WordDocument", bais);
            //输出文件
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/msword");//导出word格式
            response.addHeader("Content-Disposition", "p_w_upload;filename=" +
                    new String((documentEntry.getName() + ".doc").getBytes(), "iso-8859-1"));
//            response.setHeader("Content-disposition", "attachment;filename="+docName+".doc");
            OutputStream ostream = response.getOutputStream();
            poifs.writeFilesystem(ostream);
            bais.close();
            ostream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("toPdfFile")
    public void toPdfFile(HttpServletRequest request, HttpServletResponse response,
                          @RequestParam(name = "docName", required = true) String docName,
                          @RequestParam(name = "id", required = true) String id) {
        Doc doc = docService.getById(id);
        String path1 = uploadpath + File.separator + doc.getFileKk();
        File file = new File(path1);//需要转换的文件
        try {
            File newFile = new File(uploadpath);//转换之后文件生成的地址
            if (!newFile.exists()) {
                newFile.mkdirs();
            }
            //文件转化
            String path = uploadpath + File.separator + docName + ".pdf";
            File filePdf = new File(path);//转换之后文件生成的地址
            if (!filePdf.exists()) {
                filePdf.createNewFile();
            }
            MsOffice2Pdf.word2PDF(path1, path);
            //使用response,将pdf文件以流的方式发送的前段
            ServletOutputStream outputStream = response.getOutputStream();
            InputStream in = new FileInputStream(new File(path));// 读取文件
            // copy文件
            int i = IOUtils.copy(in, outputStream);
            addCount(id); // 统计点击量
            in.close();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("doLoad")
    public Result<?> doload(HttpServletRequest request, HttpServletResponse response,
                            @RequestParam(name = "docName", required = true) String docName,
                            @RequestParam(name = "id", required = true) String id) {
        Doc doc = docService.getById(id);
//        System.out.println("====================" + doc);
        if (doc == null) {
            return Result.error("未找到对应数据");
        }
        return Result.ok(doc);
    }

    @RequestMapping(value = "/doLoads")
    public Result<?> doLoads(HttpServletRequest request, HttpServletResponse response,
                             @RequestBody JSONObject jsonObject) {

        //word内容
        JSONArray recordId = jsonObject.getJSONArray("recordId");
        List<Object> listName = new ArrayList<>();
        for (int i = 0; i < recordId.size(); i++) {
            Doc doc = docService.getById(recordId.getString(i));
            if (doc.getDownload() == 0) {
                listName.add(doc);
            }
        }
        return Result.ok(listName);
    }

    @RequestMapping("hisPdfFile")
    public void hisPdfFile(HttpServletRequest request, HttpServletResponse response,
                           @RequestParam(name = "docName", required = true) String docName,
                           @RequestParam(name = "id", required = true) String id) {
        Doc doc = docService.getById(id);
        DocHistoryCopy docHistoryCopy = iDocHistoryCopyService.getById(id);
        String path1 = uploadpath + File.separator + docHistoryCopy.getFileKk();
        //String path1 = uploadpath + "" + doc.getFileKk();
        File file = new File(path1);//需要转换的文件

        try {
            File newFile = new File(uploadpath);//转换之后文件生成的地址
            if (!newFile.exists()) {
                newFile.mkdirs();
            }
            //文件转化
            String path = uploadpath + File.separator + docName + ".pdf";
            File filePdf = new File(path);//转换之后文件生成的地址
            if (!filePdf.exists()) {
                filePdf.createNewFile();
            }
            MsOffice2Pdf.word2PDF(path1, path);
            //使用response,将pdf文件以流的方式发送的前段
            ServletOutputStream outputStream = response.getOutputStream();
            InputStream in = new FileInputStream(new File(path));// 读取文件
            // copy文件
            int i = IOUtils.copy(in, outputStream);
            in.close();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @RequestMapping("poiHeader")
    public String poiHeader(HttpServletRequest request, HttpServletResponse response,
                           @RequestParam(name = "filePath", required = true) String filePath) {
        String path = uploadpath + File.separator + filePath;
        JSONObject jsonObject = new JSONObject();
        File is = new File(path);//文件路径
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日");
        SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            FileInputStream fis = new FileInputStream(is);
            XWPFDocument docx = new XWPFDocument(fis);
            List<XWPFHeader> headerList = docx.getHeaderList();
            if (headerList.isEmpty()){
                jsonObject.put("msg","该文档无页眉！");
                jsonObject.put("success","1");
                return jsonObject.toJSONString();
            }
            XWPFTable xwpfTable =null;
            for (XWPFHeader xwpfHeader : headerList) {
                List<XWPFTable> tables = xwpfHeader.getTables();
                for (XWPFTable table : tables) {
                    if (table.getNumberOfRows()>3){
                        xwpfTable=table;
                    }
                }
            }
            /*XWPFHeader xwpfHeader = headerList.get(0);
            List<XWPFTable> tables = xwpfHeader.getTables();
            XWPFTable xwpfTable = tables.get(0);*/
            XWPFTableRow row = xwpfTable.getRow(0);
            XWPFTableCell cell = row.getCell(0);
            String docNo = getValue(cell);
            jsonObject.put("docNo",docNo);
            XWPFTableCell cell1 = row.getCell(1);
            String sxTime = getValue(cell1);
            if (sxTime==null){
                jsonObject.put("sxTime",null);
            }else {
                Date parse1 = simpleDateFormat.parse(sxTime);
                jsonObject.put("sxTime",simpleDateFormat1.format(parse1));
            }

            XWPFTableRow row1 = xwpfTable.getRow(1);
            XWPFTableCell cell2 = row1.getCell(0);
            String categoryName = getValue(cell2);
            jsonObject.put("categoryName",categoryName);
            XWPFTableCell cell21 = row1.getCell(1);
            String updateTime = getValue(cell21);
            if (updateTime==null){
                jsonObject.put("updateTime",null);
            }else {
                Date parse = simpleDateFormat.parse(updateTime);
                jsonObject.put("updateTime",simpleDateFormat1.format(parse));
            }


            XWPFTableRow row2 = xwpfTable.getRow(2);
            XWPFTableCell cell3 = row2.getCell(0);
            String dzDepartMent = getValue(cell3);
            jsonObject.put("dzDepartment",dzDepartMent);
            XWPFTableCell cell31 = row2.getCell(1);
            String audit = getValue(cell31);
            jsonObject.put("audit",audit);
            jsonObject.put("success","0");
            jsonObject.put("msg","成功！");
        } catch (IOException | ParseException e) {
            e.printStackTrace();
        }
        return jsonObject.toJSONString();
    }
    private static String getValue(XWPFTableCell xwpfTableCell){
        String text = xwpfTableCell.getText();
        String regets = ":|：|\\s+";
        String[] split = text.split(regets);
        if (split.length==1){
            return null;
        }else {
            return split[1];
        }
    }

}
